import { isNullOrUndefined } from './index'
import { useUserStore } from '@/store'

const preFix = import.meta.env.VITE_CACHE_PREFIX

/**
 * 存储介质适配器
 * @param isSessionStorage
 * @returns
 */
const cacheAdapter = (isSessionStorage: boolean) => {
  return isSessionStorage ? sessionStorage : localStorage
}

export const cache = {
  /**
   *
   * @param key 键
   * @param value 存储的值
   * @param isSessionStorage  true => sessionStorage, false => localStorage
   */
  set(key: string, value: any, isSessionStorage = false) {
    const { userInfo } = useUserStore()
    key = key === 'token' ? preFix + key : preFix + userInfo.username + '-' + key
    cacheAdapter(isSessionStorage).setItem(key, isNullOrUndefined(value) ? value : JSON.stringify(value))
  },

  /**
   *
   * @param key 键
   * @param isSessionStorage  true => sessionStorage, false => localStorage
   * @returns 值
   */
  get<T = any>(key: string, isSessionStorage = false) {
    const { userInfo } = useUserStore()
    key = key === 'token' ? preFix + key : preFix + userInfo.username + '-' + key
    const value = cacheAdapter(isSessionStorage).getItem(key)
    return isNullOrUndefined(value) ? (value as T) : (JSON.parse(value as string) as T)
  },

  /**
   *
   * @param key 键
   * @param isSessionStorage  true => sessionStorage, false => localStorage
   */
  remove(key: string, isSessionStorage = false) {
    const { userInfo } = useUserStore()
    key = key === 'token' ? preFix + key : preFix + userInfo.username + '-' + key
    cacheAdapter(isSessionStorage).removeItem(key)
  },

  /**
   *
   * @param isSessionStorage  true => sessionStorage, false => localStorage
   */
  clear(isSessionStorage = false) {
    cacheAdapter(isSessionStorage).clear()
  },

  /**
   * 清空所有缓存 sessionStorage 和 localStorage
   */
  clearAll() {
    localStorage.clear()
    sessionStorage.clear()
  },

  /**
   * 获取token
   */
  getToken() {
    return this.get('token', true)
  },

  /**
   * 设置token
   * @param token
   */
  setToken(token: string) {
    this.set('token', token, true)
  }
}
